<?php

namespace App\Http\Controllers\Pay;

use App\Http\Controllers\Controller;
use App\Models\Pay\Others;
use App\Models\Pay\OthersPerson;
use App\Models\Personnel\Personnel;
use Illuminate\Http\Request;

class PayOthersController extends Controller
{
    public function payOthersList(Request $request)
    {
        $params = $countParams = $request->all();
        unset($countParams['pageNumber'], $countParams['pageSize']);

        $data = $this->getOthersList($params)
            ->orderByDesc('created_at')
            ->get()
            ->toArray();
        if ($data) {
            $data = $this->transData($data);
        }
        $dataCount = $this->getOthersList($countParams)->count();

        return response()->formatJson(['payOthersList' => $data, 'count' => $dataCount]);
    }

    public function getOthersList($params): \Illuminate\Database\Eloquent\Builder
    {
        $query = Others::query()->with('person');

        if (isset($params['month'])) {
            $query->where('month', date('Y-m-01', strtotime($params['month'])));
        }

        if (isset($params['pageNumber'], $params['pageSize'])) {
            $query
                ->limit($params['pageSize'])
                ->offset(($params['pageNumber'] - 1) * $params['pageSize']);
        }

        return $query;
    }

    /**
     * 数据转化
     *
     * @param  array  $data
     *
     * @return array
     */
    public function transData(array $data): array
    {
        $objectType = [
            '所有人员',
            '选择人员',
        ];
        foreach ($data as $key => $cost) {
            $data[$key]['personCount'] = ! empty($cost['person']) ? count($cost['person']) : 0;
            $data[$key]['object'] = $objectType[$cost['object_type']];
            $data[$key]['month'] = date('Y-m', strtotime($cost['month']));
        }

        return $data;
    }

    /**
     * 创建车辆信息
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function store(Request $request)
    {
        $params = $request->all();
        $payOthers = new Others($params);
        $result = $payOthers->save();
        $message = $result ? '添加成功' : '添加失败';

        if ((int) $params['object_type'] === 0) {
            $personnel = Personnel::query()->pluck('id')->toArray();
        } else {
            $personnel = explode(',', $params['depIds']);
        }

        $personnelInsert = [];
        foreach ($personnel as $v) {
            $personnelInsert[] = ['personnel_id' => $v];
        }

        if ($personnelInsert) {
            foreach ($personnelInsert as $v) {
                $payOthersPerson = new OthersPerson($v);
                $payOthers->person()->save($payOthersPerson);
            }
        }

        return response()->formatJson($result, $message);
    }

    public function edit($id)
    {
        $cost = Others::query()->with('person')->where('id', $id)->first()->toArray();

        $personIds = array_column($cost['person'], 'personnel_id');

        $personnel = Personnel::all()->groupBy('type')->toArray();

        $tree = [];
        if ($personnel) {
            foreach ($personnel as $type => $person) {
                $child = [
                    'title'  => $type === 1 ? '驾驶员' : '行政',
                    'expand' => false,
                ];
                foreach ($person as $k => $v) {
                    $v['title'] = $v['name'];
                    $v['expand'] = true;
                    if ($personIds && $cost['object_type'] === 1) {
                        $v['checked'] = in_array((string) $v['id'], $personIds, true);
                    }
                    $child['children'][] = $v;
                }
                $tree[] = $child;
            }
        }

        return response()->formatJson(['formData' => $cost, 'treeData' => $tree]);
    }

    /**
     * 修改文章
     *
     * @param  Request  $request
     * @param           $id
     *
     * @return mixed
     */
    public function update(Request $request, $id)
    {
        $params = $request->all();
        $payOthers = Others::query()->find($id);
        $params['month'] = date('Y-m-d', strtotime($params['month']));

        $result = $payOthers->update($params);

        // 删除关联数据
        $payOthers->person()->delete();

        if ((int) $params['object_type'] === 0) {
            $personnel = Personnel::query()->pluck('id')->toArray();
        } else {
            $personnel = explode(',', $params['depIds']);
        }

        $personnelInsert = [];
        foreach ($personnel as $v) {
            $personnelInsert[] = ['personnel_id' => $v];
        }

        if ($personnelInsert) {
            foreach ($personnelInsert as $v) {
                $payOthersPerson = new OthersPerson($v);
                $payOthers->person()->save($payOthersPerson);
            }
        }
        $message = $result ? '修改成功' : '修改失败';

        return response()->formatJson($result, $message);
    }

    /**
     * 删除车辆信息
     *
     * @param  Request  $request
     *
     * @return mixed
     */
    public function destroy(Request $request)
    {
        $result = false;
        if ($request->has('ids')) {
            $ids = explode(',', $request['ids']);
            $count = Others::destroy($ids);
            $result = $count !== 0;
        }

        $message = $result ? '删除成功' : '删除失败';

        return response()->formatJson($result, $message);
    }
}
